package com.amado.course36ByteStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
	public static void main(String[] args) {
		File srcDirectory = new File("F:\\html");
		File[] files = srcDirectory.listFiles();
		copyFile(files);
	}

	public static void copyFile(File[] direcotoryArray) {
		for (File file : direcotoryArray) {
			//如果是一个文件夹
			if (file.isDirectory()) {
				//递归调用（子文件）
				copyFile(file.listFiles());
			} else {
				// 不存在创建文件夹    F:/抽奖活动需求/abc.txt-->E:/抽奖活动需求/abc.txt 
				String newFileString = file.getAbsolutePath().replace("F:", "E:");
				System.out.println(file);
				//E:/抽奖活动需求/abc.txt 文件对象
				File newFile = new File(newFileString);
				//文件的父路径是否存在
				if (!newFile.getParentFile().exists()) {
					newFile.getParentFile().mkdirs();
				}
//				try {
					//newFile.createNewFile();
					cope(file,newFile);
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}
		}
	}

	private static void cope(File srcFile, File descFile) {
		InputStream input = null;
		OutputStream output = null;
		try {
			byte[] readByte = new byte[1024];
			input = new FileInputStream(srcFile);
			output = new FileOutputStream(descFile);
			int length = 0;
			while ((length=input.read(readByte)) != -1) {
				output.write(readByte, 0, length);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				input.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
